<script setup>
import api from '../api/itinerary_api.js'  // 行程接口路径
import { ref, onMounted } from "vue";
import {ElMessageBox, ElMessage, roleTypes} from "element-plus";
import lodash from 'lodash'
import itinerary_detail_api from "@/api/itinerary_detail_api.js";

// 数据定义区域
const tableData = ref([]);
const total = ref(0);
const editWinVisible = ref(false);
const detailWinVisible = ref(false);  // 新增：详情窗口可见性
const detailList = ref([]);
const generateWinVisible = ref(false); // 新增：生成行程窗口可见性

const searchObj = ref({
  current: 1,
  limit: 10,
  user_id: '',
  city: ''
});
// 当前登录用户信息
const loginUser = ref({
  role: localStorage.getItem("role") || "admin", // 默认为admin，实际应该从登录信息中获取
  id: localStorage.getItem("userId") || null
})
const obj = ref({});

// 新增：生成行程表单数据
const generateForm = ref({
  user_id: '', // 将在打开对话框时自动填充
  city: '北京', // 目前只支持北京
  days: 3,
  preferences: ''
});

// 查询方法
const search = async () => {
  const result = await api.pageWithDetails(searchObj.value);
  tableData.value = result.data;
  total.value = result.count;
};

onMounted(async () => {
  await search();
});

const editCancel = () => {
  obj.value = {};
  editWinVisible.value = false;
};

// 新增：生成行程取消操作
const generateCancel = () => {
  generateForm.value = {
    user_id: '',
    city: '北京',
    days: 3,
    preferences: ''
  };
  generateWinVisible.value = false;
};

// 新增：生成行程提交操作
const generateCommit = async () => {
  try {
    // 检查必填字段
    if (!generateForm.value.user_id) {
      ElMessage.error('用户ID不能为空');
      return;
    }

    const response = await api.generate(generateForm.value);
    if (response) {
      ElMessage.success('行程生成成功');
      generateCancel();
      await search(); // 重新加载行程列表
    }
  } catch (error) {
    console.error('生成行程失败:', error);
    if (error.response) {
      switch (error.response.status) {
        case 400:
          // 显示服务器返回的具体错误信息
          if (error.response.data && error.response.data.msg) {
            ElMessage.error('请求错误: ' + error.response.data.msg);
          } else {
            ElMessage.error('请求参数错误，请检查输入内容');
          }
          break;
        case 405:
          ElMessage.error('接口不可用，请联系管理员检查后端接口配置');
          break;
        case 500:
          if (error.response.data && error.response.data.msg) {
            ElMessage.error('服务器内部错误: ' + error.response.data.msg);
          } else {
            ElMessage.error('服务器内部错误，请联系管理员');
          }
          break;
        default:
          ElMessage.error('生成行程失败: ' + (error.message || '未知错误'));
      }
    } else {
      ElMessage.error('网络错误，请检查服务器连接');
    }
  }
};

const handleDetail = async (row) => {
  try {
    // 调用行程API的getDetails方法获取当前行程的详细信息
    const result = await api.getDetails(row.id);

    // 检查返回的数据
    if (result) {
      detailList.value = Array.isArray(result) ? result : (result.data ? result.data : [result]);
      detailWinVisible.value = true;
    } else {
      detailList.value = [];
      ElMessage.warning('未获取到行程详情数据');
      detailWinVisible.value = true;
    }
  } catch (error) {
    console.error('获取行程详情失败:', error);
    detailList.value = [];
    ElMessage.error('获取行程详情失败: ' + (error.message || '未知错误'));
    detailWinVisible.value = true;
  }
};
const editCommit = async () => {
  if (obj.value.id) {
    await api.edit(obj.value);
  } else {
    await api.add(obj.value);
  }
  search();
  editWinVisible.value = false;
};

const handleSearch = () => {
  searchObj.value.current = 1;
  search();
};

const handleSizeChange = (val) => {
  searchObj.value.limit = val;
  search();
};

const handleCurrentChange = (val) => {
  searchObj.value.current = val;
  search();
};
// 判断是否为管理员登录
const isAdminLogin = () => {
  return loginUser.value.role === 'admin';
}
const handleAdd = () => {
  obj.value = {
    user_id: '',
    city: '',
    start_date: '',
    days: 1,
    preferences: ''
    // 移除 is_deleted 字段
  };
  editWinVisible.value = true;
};

// 新增：处理生成行程
const handleGenerate = () => {
  // 自动获取当前登录用户的ID
  const userId = localStorage.getItem("userId");
  if (!userId) {
    ElMessage.error('无法获取当前用户信息，请重新登录');
    return;
  }

  generateForm.value = {
    user_id: userId,
    city: '北京',
    days: 3,
    preferences: ''
  };
  generateWinVisible.value = true;
};

const handleEdit = (index, row) => {
  obj.value = lodash.clone(row);
  // 处理日期格式
  if (row.start_date) {
    obj.value.start_date = new Date(row.start_date);
  }
  editWinVisible.value = true;
};

const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行程吗？',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error'
      }
  )
      .then(async () => {
        await api.del(row.id);
        searchObj.value.current = 1;
        search();
      })
      .catch(() => {});
};
</script>


<template>
  <div class="itinerary-management-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchObj" style="margin-top: 10px; margin-bottom: 15px;">
      <el-form-item label="用户名">
        <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item label="城市">
        <el-input v-model="searchObj.city" placeholder="请输入城市名称" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
<!--      <el-form-item>-->
<!--        <el-button type="primary" @click="handleAdd">新增</el-button>-->
<!--      </el-form-item>-->
      <el-form-item v-if="!isAdminLogin()">
        <el-button type="success" @click="handleGenerate">生成行程</el-button>
      </el-form-item>
    </el-form>

    <!-- 行程列表 -->
    <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px;"
        border
        stripe
        :header-cell-style="{ 'background-color': '#f5f7fa', 'font-weight': 'bold' }"
    >
<!--      <el-table-column label="ID" width="80" align="center">-->
<!--        <template #default="scope">-->
<!--          {{ scope.row.id }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="用户" min-width="120">
        <template #default="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="城市" min-width="150">
        <template #default="scope">
          {{ scope.row.city }}
        </template>
      </el-table-column>
      <el-table-column label="开始日期" min-width="150">
        <template #default="scope">
          {{ scope.row.start_date }}
        </template>
      </el-table-column>
      <el-table-column label="行程天数" min-width="120">
        <template #default="scope">
          <el-tag type="info">{{ scope.row.days }} 天</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="偏好" min-width="200">
        <template #default="scope">
          {{ scope.row.preferences }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleDetail(scope.row)">详情</el-button>
<!--          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>-->
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              style="margin-left: 5px;"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 30, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="text-align: right; margin-top: 10px;"
    />

    <!-- 编辑/新增对话框 -->
    <el-dialog v-model="editWinVisible" title="编辑行程信息" width="600px">
      <el-form :model="obj" label-width="100px">
        <el-form-item label="ID" v-if="obj.id">
          <el-input v-model="obj.id" disabled />
        </el-form-item>
        <el-form-item label="用户ID" required>
          <el-input v-model="obj.user_id" autocomplete="off" />
        </el-form-item>
        <el-form-item label="城市" required>
          <el-input v-model="obj.city" autocomplete="off" />
        </el-form-item>
        <el-form-item label="开始日期" required>
          <el-date-picker
              v-model="obj.start_date"
              type="date"
              placeholder="选择开始日期"
              style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="行程天数" required>
          <el-input
              v-model="obj.days"
              autocomplete="off"
              type="number"
              min="1"
          />
        </el-form-item>
        <el-form-item label="偏好">
          <el-input
              type="textarea"
              v-model="obj.preferences"
              autocomplete="off"
              rows="3"
              placeholder="例如：美食、购物、自然风光等"
          />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 生成行程对话框 -->
    <el-dialog v-model="generateWinVisible" title="生成行程" width="600px">
      <el-form :model="generateForm" label-width="100px">
        <el-form-item label="用户ID" required>
          <el-input v-model="generateForm.user_id" autocomplete="off" placeholder="请输入用户ID" disabled />
        </el-form-item>
        <el-form-item label="城市" required>
          <el-input v-model="generateForm.city" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="行程天数" required>
          <el-input-number
              v-model="generateForm.days"
              :min="1"
              :max="10"
              controls-position="right"
              style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="偏好">
          <el-input
              type="textarea"
              v-model="generateForm.preferences"
              autocomplete="off"
              rows="4"
              placeholder="请输入景点偏好，如：历史、自然、体育、购物等，多个偏好用逗号分隔"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="generateCancel">取消</el-button>
          <el-button type="primary" @click="generateCommit">生成行程</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog v-model="detailWinVisible" title="行程详情" width="800px">
      <el-table
          :data="detailList"          style="width: 100%"
          border
          stripe
      >
        <el-table-column label="天数" prop="day_number" min-width="80">
          <template #default="scope">
            第 {{ scope.row.day_number }} 天
          </template>
        </el-table-column>
        <el-table-column label="景点名称" prop="attraction_name" min-width="150">
          <template #default="scope">
            {{ scope.row.attraction_name || '未知景点' }}
          </template>
        </el-table-column>
        <el-table-column label="参观时间" prop="visit_time" min-width="120">
          <template #default="scope">
            {{ scope.row.visit_time || '未指定' }}
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="notes" min-width="200">
          <template #default="scope">
            {{ scope.row.notes || '无备注' }}
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailWinVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
